<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="modalTitle"
    @ok="onButtonOkClick"
    width="600px"
  >
    <BasicTable
      @register="registerMemberListTable"
      :can-resize="true"
      :bordered="true"
      :striped="true"
      :loading="false"
      :data-source="teamMembersData.members"
    />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, inject, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';

  import { getDeptStaffs, getAllDutyStaff } from '/@/api/duty/dutystaff';
  import { memberListTableColumns } from './dutyteam.data';
  import { addTeamMembers } from '/@/api/duty/dutyteam';
  import { DutyTeamAddMembersDto } from '/@/api/duty/model/dutyTeamModel';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { BasicTable, useTable } from '/@/components/Table';

  import { useGlobSetting } from '/@/hooks/setting';

  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'SetDutyTeamMembers',
    components: { BasicModal, BasicTable },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      //弹出窗口界面是关联部门设置
      const op = ref(OperationTypeEnum.UN_KNOWN);
      //标题--根据传入的模块名称+操作类型组合得到
      const modalTitle = ref('标题');
      const MembersModuleName = inject<string>('MembersModuleName');

      //获取项目编码
      const { globalProjectCode } = useGlobSetting();
      const projectCode = ref<String>(globalProjectCode);

      //班值id
      const dataId = ref('');
      //分组所属部门id
      let deptid = 0;

      const [registerMemberListTable, { getSelectRowKeys, clearSelectedRowKeys }] = useTable({
        title: '值班人员列表',
        // api: getDeptStaffs,
        columns: memberListTableColumns, //表头数据
        showTableSetting: true, //是否显示表格设置
        bordered: true,
        showIndexColumn: false,
        pagination: false, //关闭分页
        rowSelection: { type: 'checkbox' },
        rowKey: 'id',
        clickToRowSelect: false, //开启点击行选中/取消checkbox
      });

      /**
       * 接收父组件传递的数据并处理
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        //接收父组件传递的数据
        console.log(data);
        //判断是否传入op属性
        if (data?.op) {
          op.value = data.op;
        }

        //接收班值ID
        if (data?.dataId) {
          dataId.value = data.dataId;
        }
        //接收分组所属部门id
        if (data?.deptid) {
          deptid = data.deptid;
        }

        if (MembersModuleName) {
          modalTitle.value = unref(MembersModuleName);
        }
        if (op.value != OperationTypeEnum.UN_KNOWN && op.value != OperationTypeEnum.CUSTOME) {
          modalTitle.value += '--' + op.value;
        }

        setModalProps({ confirmLoading: false });

        if (projectCode.value === 'yzh') {
          getDutyTeamMembersByDeptId();
        } else {
          getAllDutyTeamMembers();
        }
      });

      //返回的table数据
      const teamMembersData = reactive({
        members: [],
      });

      /**
       * 获取指定部门人员列表
       */
      async function getDutyTeamMembersByDeptId() {
        //更新数据前先清空原来的数据，否则页面不刷新显示最新数据
        if (teamMembersData.members.length > 0) {
          teamMembersData.members = [];
        }
        //调用后端接口获取数据
        getDeptStaffs(deptid)
          .then((res) => {
            console.log('res', res);
            if (res != null) {
              //处理返回数据
              res.forEach((member) => {
                let result = {
                  id: member.id,
                  name: member.name,
                  deptid: member.dept,
                  phone: member.phone,
                  cornet: member.cornet,
                };
                teamMembersData.members.push(result);
              });
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            // createMessage.error(ex.msg);
          });
      }

      /**
       * 获取所有值班人员列表
       */
      async function getAllDutyTeamMembers() {
        //更新数据前先清空原来的数据，否则页面不刷新显示最新数据
        if (teamMembersData.members.length > 0) {
          teamMembersData.members = [];
        }
        //调用后端接口获取数据
        getAllDutyStaff()
          .then((res) => {
            console.log('res', res);
            if (res != null) {
              //处理返回数据
              res.forEach((member) => {
                let result = {
                  id: member.id,
                  name: member.name,
                  deptid: member.dept,
                  phone: member.phone,
                  cornet: member.cornet,
                };
                teamMembersData.members.push(result);
              });
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            // createMessage.error(ex.msg);
          });
      }

      /**
       * 点击确认按钮，设置班值成员
       */
      async function onButtonOkClick() {
        //获取选中的人员id集合
        let memberids = getSelectRowKeys();
        // console.log('班值id：', dataId.value);
        // console.log('选中的人员ID：', memberids);

        let teamMembers: DutyTeamAddMembersDto = {
          id: dataId.value,
          memberids: memberids,
        };

        setModalProps({ confirmLoading: true });
        //调用接口进行保存
        addTeamMembers(teamMembers)
          .then((res) => {
            if (!res || Object.keys(res).length == 0) {
              createMessage.success('设置成功', 2);
            }
            closeModal();
            emit('success');
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });

        //清空选中的行
        clearSelectedRowKeys();
      }

      return {
        op,
        modalTitle,
        MembersModuleName,
        registerModal,
        registerMemberListTable,
        onButtonOkClick,
        teamMembersData,
        getDutyTeamMembersByDeptId,
        getAllDutyTeamMembers,
      };
    },
  });
</script>
